using System;
using rpxnow_library.conf;

namespace rpxlogindemo.pages
{
    /// <summary>
    /// Summary description for BasePage
    /// </summary>
    abstract public class BasePage : System.Web.UI.Page
    {
        private const string STR_PostbackURLDidNotMatchOneGivenByInitialRequest = "Postback URL did not match one given by initial request";
        private const string STR_RawUrl = "RawUrl";

        public BasePage()
        {
        }

        protected override void OnLoad(EventArgs e)
        {
            if (IsPostBack)
                this.PerformCrossSiteScriptPreventCheck();

            base.OnLoad(e);
        }

        protected override void OnLoadComplete(EventArgs e)
        {
            if (!IsPostBack)
                this.DataBind();

            base.OnLoadComplete(e);
        }

        protected override void OnPreRender(EventArgs e)
        {
            this.ApplyPageTitle();

            this.IncludeMetaTags();

            this.IncludeScripts();

            this.RenderFavIcon();

            base.OnPreRender(e);
        }

        protected override void OnPreRenderComplete(EventArgs e)
        {
            this.PrepareAgainstCrossSiteScriptPreventCheck();

            base.OnPreRenderComplete(e);
        }

        private void PrepareAgainstCrossSiteScriptPreventCheck()
        {
            if (!IsPostBack)
                ViewState[STR_RawUrl] = Request.RawUrl;
        }

        private void PerformCrossSiteScriptPreventCheck()
        {
            string RawUrl = Request.RawUrl;
            if (RawUrl.EndsWith("?"))
                RawUrl = RawUrl.Substring(0, RawUrl.Length - 1);

            string CompareUrl = (string)ViewState[STR_RawUrl];
            if (!string.IsNullOrEmpty(CompareUrl))
            {
                if (CompareUrl.EndsWith("?"))
                    CompareUrl = CompareUrl.Substring(0, CompareUrl.Length - 1);

                if (!RawUrl.Equals(CompareUrl, StringComparison.InvariantCultureIgnoreCase))
                {
                    Response.StatusCode = 403;
                    Response.StatusDescription = STR_PostbackURLDidNotMatchOneGivenByInitialRequest;
                }
            }
        }

        private void ApplyPageTitle()
        {
            if (!string.IsNullOrEmpty(Page.Title))
                Page.Title = string.Format("{0}: {1}", ApplicationConfiguration.SiteTitle, Page.Title);
            else
                Page.Title = ApplicationConfiguration.SiteTitle;
        }

        private void RenderFavIcon()
        {
            // Define an HtmlLink control.
            var favIcon = new System.Web.UI.HtmlControls.HtmlLink();
            favIcon.Attributes.Add("rel", "shortcut icon");
            favIcon.Href = string.Concat(Request.Url.GetLeftPart(UriPartial.Authority), System.Web.VirtualPathUtility.ToAbsolute("~/images/logos/favicon.ico"));

            // Add the HtmlLink to the Head section of the page.
            Page.Header.Controls.Add(favIcon);
        }

        #region Render JavaScript Includes

        private void IncludeScripts()
        {
            foreach (string script in BasePage.JavaScriptIncludeFiles)
            {
                var litScript = new System.Web.UI.WebControls.Literal();
                litScript.Text = string.Format("<script type=\"text/javascript\" src=\"{0}\"></script>", JavaScriptIncludeFilePath(script));
                Page.Header.Controls.Add(litScript);
            }
        }

        static private string[] JavaScriptIncludeFiles
        {
            get
            {
                return new string[] { 
                    "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js",
                    "linkexternal.js"
                };
            }
        }

        private string JavaScriptIncludeFilePath(string script)
        {
            if (script.StartsWith("http://"))
                return script;
            else
                return string.Format("{0}/{1}", Page.ResolveClientUrl("~/js"), script);
        }

        #endregion Render JavaScript Includes

        #region Render Meta Tags

        private void IncludeMetaTags()
        {
            this.IncludeMetaTag("description", ApplicationConfiguration.MetaDescription);
            this.IncludeMetaTag("keywords", ApplicationConfiguration.MetaKeywords);
        }

        private void IncludeMetaTag(string Name, string Content)
        {
            if (string.IsNullOrEmpty(Content))
                return;

            var litMetaDescription = new System.Web.UI.WebControls.Literal();
            litMetaDescription.Text = string.Format("<meta name=\"{0}\" content=\"{1}\" />", Name, Content);
            Page.Header.Controls.Add(litMetaDescription);
        }


        #endregion Render Meta Tags
    }
}